// components/uploader/index.js
import util from '../../utils/util'

var tempUploadFiles = []

Component({

    behaviors: ['wx://form-field'],

    /**
     * 组件的属性列表
     */
    properties: {
        title: {
            type: String,
            value: '图片上传'
        },
        name: String,
        value: {
            type: Array
        },
        count: {
            type: Number,
            value: 2
        },
        files: {
            type: Array,
            value: [],
            observer: 'changeFilesValue'
        },
        attentionText: {
            type: String,
            value: 'XXXX仅需上传一张图片'
        },
        uploadStatus: {
            type: String,
            value: 'normal'
        },
        isUpload: {
            type: Boolean,
            value: false,
            observer: 'changeUploadStatus'
        },
        uploadUrl: String,
        sourceType: {
            type: String,
            observer: 'changeSourceTypeValue',
            value: 'all'
        },
        sourceTypeArray: {
            type: Array,
            value: ['album', 'camera']
        },
        startLocation: {
            type: Boolean,
            value: false
        },
        isHide: {
            type: Boolean,
            value: false
        },
        maxSize: {
          type: Number,
          value: 10000000
        }
    },

    /**
     * 组件的初始数据
     */
    data: {

    },

    /**
     * 组件的方法列表
     */
    methods: {
        changeFilesValue(v = []) {
            console.log('changeFilesValue', v, this.data.files)
            this.setData({
                value: v || []
            })
        },
        changeSourceTypeValue(v) {
            console.log('changeSourceTypeValue', v)
            let array = []
            if (v == 'album') {
                array = ['album']
            } else if (v == 'camera') {
                array = ['camera']
            } else {
                array = ['album', 'camera']
            }
            this.setData({
                sourceTypeArray: array
            })
        },
        chooseImage() {
            // console.log('sourceTypeArray', this.data.sourceTypeArray)
            wx.chooseImage({
                sourceType: this.data.sourceTypeArray,
                count: this.data.count - this.data.files.length,
                success: (res) => {
                  console.log(res)
                  const results = [];
                  const tempFiles = res.tempFiles;
                  for (let i = 0; i < tempFiles.length; i++) {
                    let item = tempFiles[i];
                    if (item.size>this.data.maxSize) {
                        wx.showToast({
                          title: '上传图片不能大于10M,已自动为你过滤第'+(i+1)+'张图片，请重新选择!',  //标题
                          icon: 'none'       //图标 none不使用图标，详情看官方文档
                        })
                        continue
                    }
                    results.push(res.tempFilePaths[i]);
                  }
                  let imgs = this.data.files.concat(results.map(item => {
                            let i = new UploadFile(item)
                            if (this.data.startLocation) {
                                i.setLocationInfo()
                            }
                            return i
                        }))
                        // console.log('UploadFile', new UploadFile(res.tempFilePaths[0]))
                    this.setData({
                        files: imgs,
                    })
                },
            })
        },
        previewImage(e) {
            if (this.data.uploadStatus != 'normal') return;
            wx.previewImage({
                urls: this.data.files.map(item => item.baseUrl + item.url),
                current: e.currentTarget.id
            })
        },
        delete_item(e) {
            console.log(e)
            wx.showModal({
                title: '温馨提示',
                content: '是否确认删除该图片？',
                confirmText: '确定',
                cancelText: '取消',
                success: res => {
                    console.log('index', e.currentTarget.dataset.id)
                    if (res.confirm) {
                        let fs = this.data.files
                        fs.splice(e.currentTarget.dataset.id, 1)
                        let array = []
                        this.setData({
                            files: array.concat(fs)
                        })
                    }
                }
            })
        },
        handleLongTap() {
            this.setData({
                uploadStatus: 'delete'
            })
        },
        cancelDelete() {
            this.setData({
                uploadStatus: 'normal'
            })
        },
        /** */
        changeUploadStatus(isUpload) {
            // console.error(this.data.name+'--changeUploadStatus: '+isUpload)
            if (isUpload) this.uploadFiles(0)
        },
        /**上传图片*/
        uploadFiles(index) {
            if (index === 0 && tempUploadFiles.length != 0) {
                tempUploadFiles = []
            }
            console.log(this.data.name, index, 'tempUploadFiles length:', tempUploadFiles.length)
            let fileList = this.data.files
          console.log("上传文件总数--->", fileList.length)
            Promise.all(fileList.map((item, index) => { return this.uploadRequestItem(item, index) })).then(res => {
                console.log('tempUploadFiles', this.data.name, res)
                this.triggerEvent('uploadComplete', res)
            }).catch(e => {
                console.error("上传出错--->", e)
                let response = {}
                response.msg = e
                response.status = 'error'
              console.error("上传出错封装--->", response)
              this.triggerEvent('uploadComplete', response)
            })
        },
        // if (fileList.length > 0) {
        //     let targetFile = fileList[index]
        //     console.log('targetFile', targetFile)
        //     if (targetFile['id'] || targetFile.status == 'success') {
        //         targetFile.status = 'success'
        //         tempUploadFiles[index] = targetFile
        //         this.handleImagUploadComplete(index)
        //         return
        //     }
        //     wx.uploadFile({
        //         url: this.data.uploadUrl,
        //         filePath: targetFile.url,
        //         name: 'file',
        //         success: res => {
        //             var data = res.data
        //             console.log(data)
        //             let response = JSON.parse(data)
        //             targetFile.status = 'success'
        //                 // targetFile.id = response.id
        //             targetFile.url = response.data.url
        //             targetFile.baseUrl = response.data.baseUrl
        //             tempUploadFiles[index] = targetFile
        //         },
        //         fail: res => {
        //             console.log('出错', index, res)
        //             targetFile.status = 'fail'
        //             tempUploadFiles[index] = targetFile
        //         },
        //         complete: res => {
        //             this.handleImagUploadComplete(index)
        //                 // this.handleImagUploadComplete(index,  completeCallBack)
        //         }
        //     })
        // }



        /**每个文件的独立请求处理 */
        uploadRequestItem(fileItem, index) {
            return new Promise((resolve, reject) => {
                if (fileItem.id || fileItem.status == 'success') {
                    resolve(fileItem)
                } else {
                    wx.uploadFile({
                        url: this.data.uploadUrl,
                        filePath: fileItem.url,
                        name: 'file',
                        success: res => {
                            let response = JSON.parse(res.data)
                            fileItem.status = 'success'
                            fileItem.url = response.data.url
                            fileItem.baseUrl = response.data.baseUrl
                            resolve(fileItem)
                        },
                        fail: res => {
                            console.log('出错', index, res)
                            reject(new Error(`第${index+1}张图片上传失败，地址为:${fileItem.url}`))
                        }
                    })
                }
            });
        },

        /**
         * 处理每次上传完毕后执行的事件
         */
        // handleImagUploadComplete: function(index) {
        //     if (index === (this.data.files.length - 1)) {
        //         this.setData({
        //             status: 'normal',
        //             filse: tempUploadFiles
        //         })
        //         console.log('tempUploadFiles', this.data.name, tempUploadFiles)
        //             // wx.hideLoading()
        //             // console.log('检验回调函数5', typeof completeCallBack === 'function')
        //         this.triggerEvent('uploadComplete', tempUploadFiles)
        //             // typeof completeCallBack === 'function' && completeCallBack()
        //     } else {
        //         // this.uploadFiles(index + 1,completeCallBack)
        //         this.uploadFiles(index + 1)
        //     }
        // },
    }
})

class UploadFile {

    constructor(path, base, id, status) {
        this.url = path
        this.baseUrl = base || ''
        this.id = id || ''
        this.status = status || ''
    }

    setLocationInfo() {
        this.takeTime = util.formatTime(new Date())
        wx.getLocation({
                type: 'wgs84', // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
                success: (res) => {
                    this.takeAddress = res.latitude + ',' + res.longitude
                }
            })
            // console.log(this.creatTime, this.locationInfo)
    }
}
